var toolUtil = require('./toolUtil');


// /**
// * 构造失败消息
// */
exports.composeFailedMessage = function (req, errMsg, code) {

    toolUtil.doAudit(req, 'failed');

    var time = ((new Date().getTime() - req.requestStartDataTime) / 1000).toFixed(2);

    if (time > 999) {
        time = 999.00;
    }

    var serviceCode = code ? code : 1000;

    var str = serviceCode + pad(Math.round(time * 100), 5);

    return returnMessage = {
        "serviceCode": Number(str),
        "result": {
            "status": 0,
            "message": errMsg
        },
        "data": null
    }
};

exports.composeErrorMessage = function (req, err, code) {
    toolUtil.doAudit(req, 'failed');

    var time = ((new Date().getTime() - req.requestStartDataTime) / 1000).toFixed(2);

    if (time > 999) {
        time = 999.00;
    }

    var serviceCode = code ? code : 1000;

    var str = serviceCode + pad(Math.round(time * 100), 5);

    if (err.status == null) {
        err = {
            status: 0,
            message: err.message
        }
    }

    return {serviceCode: Number(str), result: err, data: null}
};


// /**
// *构造成功消息
// */
exports.composeSucceededMessage = function (req, msg, data, code) {

    if (msg == null || msg == '') {
        msg = 'Ok';
    }

    var time = ((new Date().getTime() - req.requestStartDataTime) / 1000).toFixed(2);

    if (time > 999) {
        time = 999.00;
    }

    var serviceCode = code ? code : 1000;

    var str = serviceCode + pad(Math.round(time * 100), 5);

    toolUtil.doAudit(req, 'success');

    if (data == null) {
        data = {
            message: 'OK'
        }
    }

    return returnMessage = {
        "serviceCode": Number(str),
        "result": {
            "status": 1,
            "message": msg
        },
        "data": JSON.parse(JSON.stringify(data).replace(/"_id"/g, '"objId"'))
    }
}

/**
 * 构造android推送消息
 */

exports.composeAndroidPushMessage = function (description) {
    var message = {
        "description": description,
        "notification_basic_style": 0x01,
        "open_type": 2
    };
    return message;
};

function pad(num, n) {
    return new Array(('' + num).length >= n ? 0 : n + 1 - ('' + num).length).join(0) + num;
}